package handlers

import (
	"login-server/config"
	"login-server/model"
	"login-server/services"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

// registerHandler 处理用户注册
func RegisterHandler(c *gin.Context) {
	var req model.RegisterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	err := services.Register(req.Username, req.Password, req.NickName)
	if err != nil {
		c.JSON(http.StatusConflict, gin.H{
			"error": err.Error(),
		})
		return
	}

	// 返回成功响应
	c.JSON(http.StatusCreated, gin.H{
		"message": "用户注册成功",
	})
}

// loginHandler 处理用户登录
func LoginHandler(c *gin.Context) {
	var req model.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 查找用户
	findUser, err := services.Login(req.Username, req.Password)
	if err != nil {
		c.JSON(http.StatusConflict, gin.H{
			"error": err.Error(),
		})
		return
	}

	// 生成JWT令牌
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"user_id":  findUser.ID,
		"username": findUser.Username,
		"exp":      time.Now().Add(time.Hour * time.Duration(config.GlobalConfig.JWT.ExpirationHours)).Unix(),
	})

	tokenString, err := token.SignedString([]byte(config.GlobalConfig.JWT.Secret))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "生成令牌失败"})
		return
	}

	// 返回用户数据、令牌和游戏服务器WebSocket URL
	c.JSON(http.StatusOK, model.LoginResponse{
		Token: tokenString,
		User: model.User{
			ID:        findUser.ID,
			Username:  findUser.Username,
			NickName:  findUser.NickName,
			CreatedAt: findUser.CreatedAt,
		},
		GameWS: config.GlobalConfig.GameServer.WebSocketURL,
	})
}
